//
//  MovieListViewController.m
//  UI_豆瓣扩展
//
//  Created by dllo on 15/11/8.
//  Copyright © 2015年 张磊. All rights reserved.
//

#import "MovieListViewController.h"
#import "AppTools.h"
#import "Movie.h"
#import "MovieListTableViewCell.h"
#import "MovieDeteliViewController.h"
#import "MJRefresh.h"
#import "DataBaseMovie.h"
@interface MovieListViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating,MovieListViewControllerDelegate>

@property (nonatomic, retain)UITableView *myTableView;
@property (nonatomic, retain)NSMutableArray *movieArray;
@property (nonatomic, assign)BOOL isUpLoad;

@property (nonatomic, retain) UISearchController *mySearchController;
@property (nonatomic, retain) NSMutableArray *searchArray; //搜索出的数组
@end

@implementation MovieListViewController
- (void)dealloc
{
    [_movieArray release];
    [_myTableView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor redColor];
    
    self.myTableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStylePlain];
    [self.view addSubview: self.myTableView];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [_myTableView release];
    
    
    self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    //去掉cell的分割线
    self.myTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    [self.myTableView registerClass:[MovieListTableViewCell class] forCellReuseIdentifier:@"cellMovieList"];
    [self.view addSubview:self.myTableView];
    
    self.navigationItem.title = @"电影";
    
    [_myTableView release];
    
    self.mySearchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    //UISearchController的协议
    self.mySearchController.searchResultsUpdater = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.mySearchController.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时候隐藏导航栏
    self.mySearchController.hidesNavigationBarDuringPresentation = NO;
    //设置searchBar的大小
    self.mySearchController.searchBar.frame = CGRectMake(self.mySearchController.searchBar.frame.origin.x, self.mySearchController.searchBar.frame.origin.y, self.mySearchController.searchBar.frame.size.width, 44.0);
    //searchBar自适应
    [_mySearchController.searchBar sizeToFit];
    
    //搜索数组初始化
    self.searchArray = [NSMutableArray array];
    self.movieArray = [NSMutableArray array];
    [[DataBaseMovie shareDataBase] openDB];
    [[DataBaseMovie shareDataBase] createTable];
    self.movieArray = [[DataBaseMovie shareDataBase] selectMovie];
    //searchBar设置在tableView的头部
    self.myTableView.tableHeaderView = self.mySearchController.searchBar;
    
    //注册cell
    [self.myTableView registerClass:[MovieListTableViewCell class] forCellReuseIdentifier:@"cell"];
    //去掉cell分割线
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.movieArray = [NSMutableArray array];
    
    
    
    
    //下拉刷新
    [self addHeaderRefresh];
    //请求网络
    [self getData];

    //上拉刷新
    [self addFooterRefresh];
    self.isUpLoad = NO;//默认不是上拉;
}




- (void)addHeaderRefresh
{
    //当下拉时候会触发该方法
    [self.myTableView addHeaderWithCallback:^{
        NSLog(@"下拉");
        [[DataBaseMovie shareDataBase]openDB];
        [[DataBaseMovie shareDataBase]dropTable];
        //重新请求数据
        [self getData];
        [self.myTableView headerEndRefreshing];
    }];
    //进入到应用自动刷新
    [self.myTableView headerBeginRefreshing];
}

-(void)addFooterRefresh
{
    //当上拉时候触发该方法
    [self.myTableView addFooterWithCallback:^{
        
        NSLog(@"上拉");
        self.isUpLoad = NO;
        
        // 重新请求数据
        ///        [self getAFNetWorkingData];
    }];
    //进入到应用自动刷新
    //[self.myTableView headerBeginRefreshing];
}

- (void)getData
{
    //请求网络
    NSString *urlStr = @"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/movielist.php";
    [AppTools getDataWithURL:urlStr block:^(id result) {
        
        NSMutableDictionary *Dic = result;
        NSString *reason = [Dic objectForKey:@"reason"];
        NSMutableArray *array = [Dic objectForKey:@"result"];
        
        [[DataBaseMovie shareDataBase] dropTable];
        [[DataBaseMovie shareDataBase] createTable];
        
        if ([reason isEqualToString:@"success"]) {
            for (NSMutableDictionary *dic in array) {
                Movie *movie = [[Movie alloc]init];
                [movie setValuesForKeysWithDictionary:dic];
                [self.movieArray addObject:movie];
                //                NSLog(@"=======%@",movie.movieId);
                
                [[DataBaseMovie shareDataBase] insertMovie:movie];
                [movie release];
            }
            //刷新数据
            [self.myTableView reloadData];
        }else{
            NSLog(@"请求失败");
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //如果searchController是活动状态,说明是当前正在搜索
    if (self.mySearchController.active) {
        //返回搜索的数组
        return self.searchArray.count;
    }
    else {
        return self.movieArray.count;
    }

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    static NSString *cellInd = @"cell";
//    MovieListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellInd];
//    
//    Movie *movie = [self.movieArray objectAtIndex:indexPath.row];
//    cell.aMovie = movie;
////    cell.textLabel.text = @"jjj";
//    return cell;
    static NSString *cellID = @"cellMovieList";
    MovieListTableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (Cell == nil) {
        
        Cell = [[MovieListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    //如果searchController是活动状态,说明是当前正在搜索
    if (self.mySearchController.active) {
        Movie *movie = [self.searchArray objectAtIndex:indexPath.row];
        Cell.aMovie = movie;
    }
    else {
        Movie *movie = [self.movieArray objectAtIndex:indexPath.row];
        Cell.aMovie = movie;
    }
    //设置代理人
    Cell.movieLVCDelegate = self;
    
    return Cell;
}
//协议方法实现
- (void)movieInfo:(Movie *)movie
{
    NSLog(@"name = %@ ID = %@",movie.movieName, movie.movieId);
}


//UISearchController的协议必须执行的方法
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    
    //写在搜索框中的文字
    NSString *filterString = searchController.searchBar.text;
    
    //删除搜索数组中的所有元素,一遍装入新的搜索的元素
    [self.searchArray removeAllObjects];
    
    //rangeOfString:方法是在movieName中搜索是否包含searchText
    //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
    //NSNotFound 表示请求操作的某个内容没有发现
    
    //用MovieModel遍历数据库数据的数组
    for (Movie *movie in self.movieArray) {
        //如果电影名字里有包含搜索框里的文字
        if ([movie.movieName rangeOfString:filterString].location != NSNotFound) {
            //就把这个电影Model加入到搜索数组里
            [self.searchArray addObject:movie];
        }
    }
    //刷新tableView
    [self.myTableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    
//    MovieDeteliViewController *movieDVC = [[MovieDeteliViewController alloc]init];
//    Movie *movie = [self.movieArray objectAtIndex:indexPath.row];
//    movieDVC.movieID = movie.movieId;
////    NSLog(@"-------%@",movie.movieId);
//    [self.navigationController pushViewController:movieDVC animated:YES];
//    [movieDVC release];
//    [movie release];
    MovieDeteliViewController *movieDVC = [[MovieDeteliViewController alloc] init];
    
    //如果搜索处于活动状态,用搜索数组跳转
    if (self.mySearchController.active) {
        Movie *movie = [self.searchArray objectAtIndex:indexPath.row];
        movieDVC.movieID = movie.movieId;
    }
    else {
        Movie *movie = [self.movieArray objectAtIndex:indexPath.row];
        movieDVC.movieID = movie.movieId;
    }
    [self.navigationController pushViewController:movieDVC animated:YES];
    [movieDVC release];
}

//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.mySearchController.active) {
        self.mySearchController.active = NO;
        [self.mySearchController.searchBar removeFromSuperview];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
